<?php

namespace console\controllers;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
    public function actionInit()
    {
        $auth = Yii::$app->authManager;

        $this->createInitRbac($auth);
    }

    /**
     * @param $auth \yii\rbac\ManagerInterface
     */
    private function createInitRbac($auth)
    {
        // add "create branch" permission
        $createBranch = $auth->createPermission('createBranch');
        $createBranch->description = 'allow the user to create a branch';
        $auth->add($createBranch);

        // add "create company" permission
        $createCompany = $auth->createPermission('createCompany');
        $createCompany->description = 'allow the user to create a company';
        $auth->add($createCompany);

        // add "branch admin" role
        $branchAdmin = $auth->createRole('branchAdmin');
        $auth->add($branchAdmin);
        $auth->addChild($branchAdmin, $createBranch);

        // add "admin" role
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $auth->addChild($admin, $branchAdmin);
        $auth->addChild($admin, $createCompany);

        // assign roles to users 1 & 3
        $auth->assign($branchAdmin, 3);
        $auth->assign($admin, 1);
    }
}